<template>
  <div>
    <el-tabs
      v-model="activeName"
      type="border-card"
      @tab-click="handleClick"
    >
      <el-tab-pane
        label="待结算"
        name="stay"
      >
        <div class="gva-table-box">
          <div style="padding-bottom: 30px;">
            <el-tag
              type="primary"
              size="large"
            >预计结算日期  :  {{ nextDate }}</el-tag>
          </div>
          <el-table
            ref="multipleTable"
            style="width: 100%"
            tooltip-effect="dark"
            :data="nowMonthDataList"
            row-key="ID"
            border="true"
            :height="nowMonthDataList && nowMonthDataList.length > 10 ? 600 : null"
            @selection-change="handleSelectionChange"
          >

            <el-table-column
              align="left"
              label="日期"
              prop="date"
            />
            <el-table-column
              align="left"
              label="广告投放收入"
              prop="advExpendIncome"
            />
            <el-table-column
              align="left"
              label="广告消耗"
              prop="noIncomeExpend"
            />
            <el-table-column
              align="left"
              label="初步利润"
              prop="noIncomeProfit"
            />
            <el-table-column
              align="left"
              label="初步分成利润"
              prop="noIncomeDividend"
            />
          </el-table>
        </div>
        <el-divider />
        <div class="gva-table-box">
          <div style="display: flex; ">
            <el-tag
              type="primary"
              style="margin-right: 20px;"
              size="large"
            >发行人计划比例:{{ issuerScale }}%</el-tag>
          </div>
          <el-table
            ref="multipleTable"
            style="width: 100%;margin-top: 20px"
            tooltip-effect="dark"
            :data="issuerData"
            :height="issuerData && issuerData.length > 10 ? 600 : null"
            row-key="ID"
            border="true"
          >
            <el-table-column
              align="left"
              label="日期"
              prop="date"
            />
            <el-table-column
              align="left"
              label="买量消耗(元)"
              prop="expense"
            />
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane
        label="已结算"
        name="already"
      >
        <div class="gva-table-box">
          <el-table
            ref="multipleTable"
            style="width: 100%"
            tooltip-effect="dark"
            :data="checkList"
            row-key="ID"
            :height="checkList && checkList.length > 10 ? 600 : null"
            border="true"
            @selection-change="handleSelectionChange"
          >

            <el-table-column
              align="left"
              label="日期"
              prop="month"
            />

            <el-table-column
              align="left"
              label="广告收入"
              prop="advIncome"
            />
            <el-table-column
              align="left"
              label="广告消耗"
              prop="noIncomeAdvExpend"
            />
            <el-table-column
              align="left"
              label="利润"
              prop="noIncomeAdvProfit"
            />
            <el-table-column
              align="left"
              label="分成利润"
              prop="noIncomeDividend"
            />
            <el-table-column
              align="left"
              label="状态"
            >
              <template #default="scope">
                {{ scope.row.status == 1 ? '校对中' : '已结算' }}
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="操作"
              fixed="right"
            >
              <template #default="scope">
                <el-button
                  v-if="scope.row.status == 2"
                  type="primary"
                  link
                  icon="Checked"
                  class="table-button"
                  @click="detail(scope.row)"
                >详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div></el-tab-pane>
    </el-tabs>

    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      :title="type==='create'?'添加':'修改'"
      destroy-on-close
    >
      <el-scrollbar height="500px">
        <el-form
          ref="elFormRef"
          :model="formData"
          label-position="right"
          :rules="rule"
          label-width="100px"
        >
          <el-form-item
            label="成本项目:"
            prop="name"
          >
            <el-input
              v-model="formData.name"
              :clearable="true"
              placeholder="请输入成本名称"
            />
          </el-form-item>
          <el-form-item
            label="渠道:"
            prop="platform_id"
          >
            <el-select
              v-model="formData.platform_id"
              placeholder="请选择渠道"
              style="width:100%"
              :clearable="true"
              @change="changePlatform"
            >
              <el-option
                v-for="(item,key) in platformOptions"
                :key="key"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="摊比(%):"
            prop="share"
          >
            <el-input
              v-model="divide"
              disabled
              style="width:100%"
              :clearable="true"
            />
          </el-form-item>
          <el-form-item
            label="成本:"
            prop="cost"
          >
            <el-input-number
              v-model="formData.cost"
              style="width:100%"
              :precision="2"

              :clearable="true"
              @change="changeCost"
            />
          </el-form-item>
          <el-form-item
            label="分摊:"
            prop="share"
          >
            <el-input
              v-model="formData.share"
              disabled
              style="width:100%"
              :clearable="true"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogCost"
      title="添加"
      destroy-on-close
    >
      <el-scrollbar height="500px">
        <el-form
          ref="elFormRefCost"
          :model="costForm"
          label-position="right"
          :rules="ruleCost"
          label-width="100px"
        >
          <el-form-item
            label="成本项目:"
            prop="name"
          >
            <el-input
              v-model="costForm.name"
              :clearable="true"
              placeholder="请输入成本名称"
            />
          </el-form-item>
          <el-form-item
            label="摊比(%):"
          >
            <el-input
              v-model="rowInfo.divide"
              disabled
              style="width:100%"
              :clearable="true"
            />
          </el-form-item>
          <el-form-item
            label="成本:"
            prop="cost"
          >
            <el-input-number
              v-model="costForm.cost"
              style="width:100%"
              :precision="2"

              :clearable="true"
              @change="changeNewCost"
            />
          </el-form-item>
          <el-form-item
            label="分摊:"
            prop="share"
          >
            <el-input
              v-model="costForm.share"
              disabled
              style="width:100%"
              :clearable="true"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCostDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterCostDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="detailDialog"
      title="账单详情"
      destroy-on-close
      width="70%"
    >
      <el-scrollbar height="800px">
        <el-card>
          <el-row :gutter="20">
            <el-col :span="5">分成比例:    {{ rowInfo.divide }}%</el-col>
            <el-col :span="5">结算时间:    {{ rowInfo.created_at.split('T')[0] }}</el-col>
          </el-row>
          <div
            class="gva-btn-list"
            style="flex-direction:row-reverse"
          >
            <el-button
              v-if="rowInfo.status == 2"
              type="info"
            >
              已结算
            </el-button>
          </div>
          <div style="display: flex;justify-content: space-around">
            <el-card style="max-width: 150px">
              <div style="padding-bottom: 20px;">
                <span>本月广告消耗(元)</span>
              </div>
              <div style="text-align: center;">
                <span>{{ checkInfo.noIncomeAdvExpend }}</span>
              </div>
            </el-card>
            <el-card style="max-width: 150px">
              <div style="padding-bottom: 20px;">
                <span>本月买量收入(元)</span>
              </div>
              <div style="text-align: center;">
                <span>{{ checkInfo.advIncome }}</span>
              </div>
            </el-card>
            <el-card style="max-width: 150px">
              <div style="padding-bottom: 20px;">
                <span>本月广告金(元)</span>
              </div>
              <div style="text-align: center;">
                <span>{{ checkInfo.grant }}</span>
              </div>
            </el-card>
            <el-card style="max-width: 180px">
              <div style="padding-bottom: 20px;">
                <span>本月其他推广成本(元)</span>
              </div>
              <div style="text-align: center;">
                <span>{{ checkInfo.cost }}</span>
              </div>
            </el-card>
            <el-card style="max-width: 150px">
              <div style="padding-bottom: 20px;">
                <span>本月总利润(元)</span>
              </div>
              <div style="text-align: center;">
                <span>{{ checkInfo.noIncomeAdvProfit }}</span>
              </div>
            </el-card>
            <el-card style="max-width: 150px">
              <div style="padding-bottom: 20px;">
                <span>本月分成利润(元)</span>
              </div>
              <div style="text-align: center;">
                <span>{{ checkInfo.noIncomeDividend }}</span>
              </div>
            </el-card>
          </div>

        </el-card>
        <el-divider />
        <el-card>
          <div style="padding-bottom: 40px;">
            <el-tag
              type="primary"
              size="large"
            >详细数据</el-tag>
          </div>
          <el-table
            ref="multipleTable"
            v-loading="loading"
            style="width: 100%"
            tooltip-effect="dark"
            :data="checkDetail"
            row-key="ID"
            :height="checkDetail && checkDetail.length > 10 ? 600 : null"
            border="true"
            @selection-change="handleSelectionChange"
          >

            <el-table-column
              align="left"
              label="日期"
              prop="date"
            />

            <el-table-column
              align="left"
              label="广告收入"
              prop="advExpendIncome"
            />
            <el-table-column
              align="left"
              label="广告消耗"
              prop="noIncomeExpend"
            />
            <el-table-column
              align="left"
              label="初步利润"
              prop="noIncomeProfit"
            />
            <el-table-column
              align="left"
              label="初步分成利润"
              prop="noIncomeDividend"
            />
          </el-table>
        </el-card>
        <el-divider />
        <el-card>
          <div style="padding-bottom: 20px;">
            <el-tag
              type="primary"
            >发行人计划比例:{{ detailScale }}%</el-tag>
          </div>
          <el-table
            ref="multipleTable"
            style="width: 100%;"
            tooltip-effect="dark"
            :data="detailIssuerData"
            row-key="ID"
            border="true"
          >
            <el-table-column
              align="left"
              label="日期"
              prop="date"
            />
            <el-table-column
              align="left"
              label="买量消耗(元)"
              prop="expense"
            />
          </el-table>
        </el-card>
        <el-divider />
        <el-card>
          <div style="padding-bottom: 10px;">
            <el-tag
              type="primary"
              size="large"
            >成本</el-tag>
          </div>
          <div
            v-if="rowInfo.status == 1"
            class="gva-btn-list"
            style="flex-direction:row-reverse"
          >
            <el-button
              type="success"
              icon="plus"
              @click="openCostDialog"
            >添加成本</el-button>
          </div>
          <el-table
            ref="multipleTable"
            style="width: 100%"
            tooltip-effect="dark"
            :data="checkCost"
            :height="checkCost && checkCost.length > 10 ? 600 : null"
            row-key="ID"
            border="true"
            @selection-change="handleSelectionChange"
          >

            <el-table-column
              align="left"
              label="成本项目"
              prop="name"
            />

            <el-table-column
              align="left"
              label="成本金额"
              prop="cost"
            />
            <el-table-column
              align="left"
              label="成本分摊比例"
            >
              <template #default="scope">
                {{ scope.row.divide }}%
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="成本分摊"
              prop="share"
            />
            <el-table-column
              v-if="rowInfo.status == 1"
              align="left"
              label="操作"
              fixed="right"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  icon="delete"
                  @click="deleteCostRow(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="closeDetailDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createQmCost,
  deleteQmCost,
  updateQmCost,
  getQmCostList
} from '@/api/qmCost'

import {
  getQmPlatformsList
} from '@/api/qmPlatforms'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'

import {
  getHugeList
} from '@/api/openApi'

defineOptions({
  name: 'QmCost'
})

// 自动化生成的字典（可能为空）以及字段
const platformOptions = ref([])
const formData = ref({
  platformId: undefined,
  name: '',
  cost: 0,
  month: '',
})

// 验证规则
const rule = reactive({
  platform_id: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  name: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  cost: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  share: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
})

const ruleCost = reactive({
  name: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  cost: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  share: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
})

const getYearMonth = () => {
  const currentDate = new Date()

  // 获取年份和月份
  const year = currentDate.getFullYear()
  const month = currentDate.getMonth() + 1
  return `${year}-${month < 10 ? '0' : ''}${month}`
}

const elFormRef = ref()
// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const activeName = ref('stay')

// 查询
const getTableData = async() => {
  const yearMonth = getYearMonth()
  const table = await getQmCostList({ month: yearMonth })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

const issuerScale = ref(0)
const handleClick = (tab, event) => {
  if (tab.props.name == 'stay') {
    getNowMonthData()
  } else {
    getCheckList()
  }
}

const showScale = () => {
  const now = new Date()

  // 获取年份和月份
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')

  // 格式化日期为 'YYYY-MM'
  const formattedDate = `${year}-${month}`
  getHugeList({ type: 'showIssuerScale', params: formattedDate }).then(res => {
    if (res.code == 0) {
      issuerScale.value = res.data.list[0].response
    }
  })
}

showScale()

const issuerData = ref([])

const formatDateMonth = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const getIssuerData = () => {
  // 获取这个月开始日期和结束日期
  const now = new Date()

  // 获取当前月的第一天
  const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)

  // 获取当前月的最后一天
  const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  const firstDayFormatted = formatDateMonth(firstDay)
  const lastDayFormatted = formatDateMonth(lastDay)
  getHugeList({ type: 'issuer', start_date: firstDayFormatted, end_date: lastDayFormatted }).then(res => {
    if (res.code === 0) {
      issuerData.value = []
      res.data.list.forEach(item => {
        const value = JSON.parse(item.response)
        value.expense = (value.expense / ((100 + Number(issuerScale.value)) / 100) / 100).toFixed(2)
        issuerData.value.push({
          date: item.date,
          expense: value.expense
        })
      }
      )
    }
  })
}
getIssuerData()

const nextDate = ref('')

const getNextDate = () => {
  const currentDate = new Date()

  // 获取下一个月的日期
  const nextMonthDate = new Date(currentDate)
  nextMonthDate.setMonth(currentDate.getMonth() + 1)

  // 设置日期为五号
  nextMonthDate.setDate(11)

  const formattedDate = nextMonthDate.toISOString().split('T')[0]
  nextDate.value = formattedDate
}

getNextDate()

const nowMonthDataList = ref([])

const getNowMonthData = () => {
  const date = getYearMonth()
  getHugeList({ type: 'monthCheck', params: date }).then(res => {
    if (res.code === 0) {
      nowMonthDataList.value = []
      res.data.list.forEach(item => {
        const value = JSON.parse(item.response)
        nowMonthDataList.value.push({
          date: item.date,
          platformId: value.platformId,
          advExpendIncome: value.advExpendIncome,
          noIncomeExpend: value.noIncomeExpend,
          noIncomeProfit: value.noIncomeProfit,
          noIncomeDividend: value.noIncomeDividend
        })
      })
    }
  })
}
const closeDetailDialog = () => {
  detailDialog.value = false
}

getNowMonthData()

const checkList = ref([])
const getCheckList = () => {
  getHugeList({ type: 'check' }).then(res => {
    if (res.code === 0) {
      checkList.value = []
      res.data.list.forEach(item => {
        const value = JSON.parse(item.response)
        checkList.value.push(value)
        console.log(value)
      })
    }
  })
}
getCheckList()

getTableData()

const detailScale = ref(0)
const detailIssuerData = ref([])

const detailDialog = ref(false)
const rowInfo = ref({})

const checkCost = ref([])
const checkDetail = ref([])
const loading = ref(false)

const checkInfo = ref({})

const dialogCost = ref(false)
const detail = async(row) => {
  checkInfo.value = {}
  detailDialog.value = true
  rowInfo.value = row
  loading.value = true
  const table = await getQmCostList({ month: row.month })
  var cost = 0
  if (table.code === 0) {
    if (table.data.list) {
      checkCost.value = table.data.list
      table.data.list.forEach(item => {
        cost += item.cost
      })
    }
  }

  rowInfo.value.divide = row.scale

  getHugeList({ type: 'showIssuerScale', params: row.date }).then(res => {
    if (res.code == 0) {
      detailScale.value = res.data.list[0].response
    }
  })

  const now = new Date()

  // 获取当前月的第一天
  const firstDay = new Date(now.getFullYear(), now.getMonth() - 1, 1)

  // 获取当前月的最后一天
  const lastDay = new Date(now.getFullYear(), now.getMonth(), 0)
  const firstDayFormatted = formatDateMonth(firstDay)
  const lastDayFormatted = formatDateMonth(lastDay)

  const result = await getHugeList({ type: 'issuer', start_date: firstDayFormatted, end_date: lastDayFormatted })
  if (result.code == 0) {
    detailIssuerData.value = []
    if (result.data.list) {
      result.data.list.forEach(item => {
        const value = JSON.parse(item.response)
        value.expense = (value.expense / ((100 + Number(detailScale.value)) / 100) / 100).toFixed(2)
        detailIssuerData.value.push({
          date: item.date,
          expense: value.expense
        })
      })
    }
  }

  getHugeList({ type: 'monthCheck', params: row.month }).then(res => {
    if (res.code === 0) {
      checkDetail.value = []

      var expend = 0
      var income = 0
      var profit = 0
      res.data.list.forEach(item => {
        const value = JSON.parse(item.response)
        checkDetail.value.push(value)
      })
      loading.value = false
    }
  })

  getHugeList({ type: 'checkInfo', params: row.id }).then(res => {
    checkInfo.value = JSON.parse(res.data.list[0].response)
  })
}

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
  platformOptions.value = await getDictFunc('platform')
}

// 获取需要的字典 可能为空 按需保留
setOptions()

const changeCost = (val) => {
  formData.value.share = (val * divide.value / 100).toFixed(2)
}

const changeNewCost = (val) => {
  costForm.value.share = (val * rowInfo.value.divide / 100).toFixed(2)
}

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteQmCostFunc(row)
  })
}

const deleteCostRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteQmCostFunc(row)
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 删除行
const deleteQmCostFunc = async(row) => {
  const res = await deleteQmCost({ ID: row.id })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
    if (rowInfo.value.id) {
      detail(rowInfo.value)
    }
  }
}

const divide = ref(0)

const changePlatform = (val) => {
  const game_id = JSON.parse(localStorage.getItem('nowGameInfo')).id
  getQmPlatformsList({ gameId: game_id, platformId: val, page: 1, pageSize: 1 }).then(res => {
    if (res.code == 0) {
      if (res.data.total > 0) {
        divide.value = res.data.list[0].divide
      } else {
        ElMessage({
          type: 'error',
          message: '请先设置该渠道'
        })
        dialogFormVisible.value = false
      }
    } else {
      ElMessage({
        type: 'error',
        message: res.msg
      })
    }
  }
  )
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
  formData.value = {
    gameHash: '',
    platformId: undefined,
    name: '',
    cost: 0,
    month: '',
    share: 0,
  }
  divide.value = 0
}

const costForm = ref({})
const openCostDialog = () => {
  dialogCost.value = true
  costForm.value = {
    gameHash: '',
    platformId: rowInfo.value.platformId,
    name: '',
    cost: 0,
    month: '',
  }
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    gameHash: '',
    platformId: undefined,
    name: '',
    cost: 0,
    month: '',
  }
}

const closeCostDialog = () => {
  dialogCost.value = false
  costForm.value = {
    gameHash: '',
    platformId: rowInfo.value.platformId,
    name: '',
    cost: 0,
    month: '',
  }
}

// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return

    formData.value.month = getYearMonth()

    let res
    switch (type.value) {
      case 'create':
        res = await createQmCost(formData.value)
        break
      case 'update':
        res = await updateQmCost(formData.value)
        break
      default:
        res = await createQmCost(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const enterCostDialog = async() => {
  if (costForm.value.name == '') {
    ElMessage({
      type: 'error',
      message: '成本项目不能为空'
    })
    return
  }

  if (costForm.value.cost == 0) {
    ElMessage({
      type: 'error',
      message: '成本金额不能为0'
    })
    return
  }

  costForm.value.month = rowInfo.value.month
  costForm.value.platformId = rowInfo.value.platformId

  const res = await createQmCost(costForm.value)
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '创建'
    })
    closeCostDialog()
    detail(rowInfo.value)
  }
}

</script>

<style>

</style>
